package com.taskmanagement.service;

import com.taskmanagement.mapper.UserMapper;
import com.taskmanagement.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 根据用户名查找用户
     */
    @Transactional(readOnly = true)
    public User findByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            logger.warn("尝试使用空用户名查找用户");
            return null;
        }

        try {
            User user = userMapper.findByUsername(username);
            logger.debug("查找用户: {}, 结果: {}", username, user != null ? "找到" : "未找到");
            return user;
        } catch (Exception e) {
            logger.error("查找用户时发生错误: {}", username, e);
            throw new RuntimeException("查找用户失败", e);
        }
    }

    /**
     * 根据邮箱查找用户
     */
    @Transactional(readOnly = true)
    public User findByEmail(String email) {
        if (!StringUtils.hasText(email)) {
            logger.warn("尝试使用空邮箱查找用户");
            return null;
        }

        try {
            User user = userMapper.findByEmail(email);
            logger.debug("查找用户: {}, 结果: {}", email, user != null ? "找到" : "未找到");
            return user;
        } catch (Exception e) {
            logger.error("根据邮箱查找用户时发生错误: {}", email, e);
            throw new RuntimeException("查找用户失败", e);
        }
    }

    /**
     * 根据ID查找用户
     */
    @Transactional(readOnly = true)
    public User findById(BigInteger id) {

        try {
            User user = userMapper.findById(id);
            logger.debug("查找用户ID: {}, 结果: {}", id, user != null ? "找到" : "未找到");
            return user;
        } catch (Exception e) {
            logger.error("根据ID查找用户时发生错误: {}", id, e);
            throw new RuntimeException("查找用户失败", e);
        }
    }

    /**
     * 检查用户名是否存在
     */
    @Transactional(readOnly = true)
    public boolean existsByUsername(String username) {
        return findByUsername(username) != null;
    }

    /**
     * 检查邮箱是否存在
     */
    @Transactional(readOnly = true)
    public boolean existsByEmail(String email) {
        return findByEmail(email) != null;
    }

    /**
     * 创建新用户
     */
    public User createUser(String username, String email, String password, String fullName) {
        // 参数验证
        validateUserInput(username, email, password, fullName);

        // 检查用户名和邮箱是否已存在
        if (existsByUsername(username)) {
            logger.warn("尝试创建已存在的用户名: {}", username);
            throw new RuntimeException("用户名已存在");
        }

        if (existsByEmail(email)) {
            logger.warn("尝试创建已存在的邮箱: {}", email);
            throw new RuntimeException("邮箱已被使用");
        }

        try {
            // 创建用户对象
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            user.setPassword(passwordEncoder.encode(password));
            user.setFullName(fullName);
            user.setEnabled(true);

            // 保存用户
            userMapper.insert(user);

            logger.info("成功创建用户: {}", username);
            return user;
        } catch (Exception e) {
            logger.error("创建用户时发生错误: {}", username, e);
            throw new RuntimeException("创建用户失败", e);
        }
    }

    /**
     * 用户注册（兼容原有方法）
     */
    public User register(User user) {
        if (user == null) {
            throw new IllegalArgumentException("用户对象不能为空");
        }

        return createUser(
                user.getUsername(),
                user.getEmail(),
                user.getPassword(),
                user.getFullName()
        );
    }

    /**
     * 更新用户信息
     */
    public User updateUser(User user) {
        if (user == null || user.getId() == null) {
            throw new IllegalArgumentException("用户对象或用户ID不能为空");
        }

        try {
            // 检查用户是否存在
            User existingUser = findById(user.getId());
            if (existingUser == null) {
                throw new RuntimeException("用户不存在");
            }

            // 如果密码有更新，需要加密
            if (StringUtils.hasText(user.getPassword())) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            }

            userMapper.update(user);
            logger.info("成功更新用户: {}", user.getUsername());
            return user;
        } catch (Exception e) {
            logger.error("更新用户时发生错误: {}", user.getUsername(), e);
            throw new RuntimeException("更新用户失败", e);
        }
    }

    /**
     * 删除用户
     */
    public void deleteUser(BigInteger userId) {
        if (userId == null ) {
            throw new IllegalArgumentException("用户ID不能为空或无效");
        }

        try {
            User user = findById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            userMapper.deleteById(userId);
            logger.info("成功删除用户: {}", user.getUsername());
        } catch (Exception e) {
            logger.error("删除用户时发生错误: {}", userId, e);
            throw new RuntimeException("删除用户失败", e);
        }
    }

    /**
     * 获取所有用户
     */
    @Transactional(readOnly = true)
    public List<User> findAllUsers() {
        try {
            List<User> users = userMapper.findAll();
            logger.debug("查询到 {} 个用户", users.size());
            return users;
        } catch (Exception e) {
            logger.error("查询所有用户时发生错误", e);
            throw new RuntimeException("查询用户列表失败", e);
        }
    }

    /**
     * 启用/禁用用户
     */
    public void toggleUserStatus(BigInteger userId, boolean enabled) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空或无效");
        }

        try {
            User user = findById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            user.setEnabled(enabled);
            userMapper.update(user);

            logger.info("用户 {} 状态已更新为: {}", user.getUsername(), enabled ? "启用" : "禁用");
        } catch (Exception e) {
            logger.error("更新用户状态时发生错误: {}", userId, e);
            throw new RuntimeException("更新用户状态失败", e);
        }
    }

    /**
     * 修改密码
     */
    public void changePassword(BigInteger userId, String oldPassword, String newPassword) {
        if (userId == null ) {
            throw new IllegalArgumentException("用户ID不能为空或无效");
        }

        if (!StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            throw new IllegalArgumentException("密码不能为空");
        }

        try {
            User user = findById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            // 验证旧密码
            if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
                throw new RuntimeException("原密码错误");
            }

            // 更新新密码
            user.setPassword(passwordEncoder.encode(newPassword));
            userMapper.update(user);

            logger.info("用户 {} 密码修改成功", user.getUsername());
        } catch (Exception e) {
            logger.error("修改密码时发生错误: {}", userId, e);
            throw new RuntimeException("修改密码失败", e);
        }
    }

    /**
     * 验证用户输入
     */
    private void validateUserInput(String username, String email, String password, String fullName) {
        if (!StringUtils.hasText(username)) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        if (!StringUtils.hasText(email)) {
            throw new IllegalArgumentException("邮箱不能为空");
        }

        if (!StringUtils.hasText(password)) {
            throw new IllegalArgumentException("密码不能为空");
        }

        if (!StringUtils.hasText(fullName)) {
            throw new IllegalArgumentException("姓名不能为空");
        }

        // 用户名长度验证
        if (username.length() < 3 || username.length() > 20) {
            throw new IllegalArgumentException("用户名长度必须在3-20个字符之间");
        }

        // 密码强度验证
        if (password.length() < 6) {
            throw new IllegalArgumentException("密码长度不能少于6个字符");
        }

        // 邮箱格式验证
        if (!email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }
    }
}
